package com.tomato.modules.account.service.impl;

import com.tomato.modules.account.constants.AccountRedisKey;
import com.tomato.modules.account.service.AccountRedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * 账户 redis 操作
 *
 * @author lizhifu
 * @date 2022/3/8
 */
@Service
public class AccountRedisServiceImpl implements AccountRedisService {
    private Logger logger = LoggerFactory.getLogger(AccountRedisServiceImpl.class);

    private static final BigDecimal MULTIPLE = new BigDecimal("100");

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
//    @Resource
//    private AccountMapper accountMapper;
    @Override
    public void accountBalance(String accountNo, BigDecimal amount) {
        //  1. 账号编号 Key
        String accountNoKey = AccountRedisKey.ACCOUNT_NO(accountNo);
        long changeAmount = amount.multiply(MULTIPLE).longValue();
        logger.info("账号编号 Key： {} 变更金额： {}",accountNoKey,changeAmount);
        //  是否存在账户 Key TODO 数据库查询共享锁、创建账户时进行 redis 数据的初始化
        if (!redisTemplate.hasKey(accountNoKey)) {
            logger.error("账号编号 Key： {} 不存在",accountNoKey);
            return;
        }
        // 2. 账户金额变动
        Long balance = redisTemplate.opsForValue().increment(accountNoKey,changeAmount);
        logger.info("账号编号 Key： {},balance： {}",accountNoKey,balance);
        // 3. 超出库存判断，进行恢复原始库存
        if (balance < 0) {
            Long backBalance = redisTemplate.opsForValue().increment(accountNoKey, - amount.multiply(MULTIPLE).longValue());
            logger.info("账号编号 Key： {},backBalance： {}",accountNoKey,backBalance);
            return;
        }
    }
}
